<template>
  <el-card>
    <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 16px;">
      <span style="font-size: 18px; font-weight: bold;">部门管理</span>
      <el-button type="primary" @click="openDialog()">新增部门</el-button>
    </div>
    <el-table :data="departments" border stripe style="width: 100%">
      <el-table-column prop="id" label="ID" width="80" />
      <el-table-column prop="name" label="部门名称" />
      <el-table-column label="操作" width="160">
        <template #default="scope">
          <el-button size="small" @click="openDialog(scope.row)">编辑</el-button>
          <el-button size="small" type="danger" @click="deleteDepartment(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-dialog :title="dialogTitle" v-model="dialogVisible" width="400px">
      <el-form :model="form" :rules="rules" ref="formRef" label-width="80px">
        <el-form-item label="部门名称" prop="name">
          <el-input v-model="form.name" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">保存</el-button>
      </template>
    </el-dialog>
  </el-card>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import api from '../api'
import { ElMessage } from 'element-plus'

const departments = ref([])
const dialogVisible = ref(false)
const dialogTitle = ref('')
const form = ref({})
const formRef = ref()

const rules = {
  name: [{ required: true, message: '请输入部门名称', trigger: 'blur' }]
}

function fetchDepartments() {
  api.get('/departments').then(res => {
    departments.value = res.data
  })
}

function openDialog(row) {
  dialogTitle.value = row ? '编辑部门' : '新增部门'
  form.value = row ? { ...row } : {}
  dialogVisible.value = true
}

function submitForm() {
  formRef.value.validate(valid => {
    if (!valid) return
    if (form.value.id) {
      api.put(`/departments/${form.value.id}`, form.value).then(() => {
        ElMessage.success('修改成功')
        dialogVisible.value = false
        fetchDepartments()
      })
    } else {
      api.post('/departments', form.value).then(() => {
        ElMessage.success('新增成功')
        dialogVisible.value = false
        fetchDepartments()
      })
    }
  })
}

function deleteDepartment(id) {
  api.delete(`/departments/${id}`).then(() => {
    ElMessage.success('删除成功')
    fetchDepartments()
  })
}

onMounted(fetchDepartments)
</script> 